package com.fattyCorps.game.service;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.fattyCorps.common.mgr.Cfg;
import com.fattyCorps.common.obj.config.MainGuanqianMould;
import com.fattyCorps.common.obj.msg.server.battle.CBattle;
import com.fattyCorps.common.obj.msg.server.battle.DHeroShort;
import com.fattyCorps.common.obj.msg.server.battle.EBattleResult;
import com.fattyCorps.common.obj.msg.server.battle.SBattleResult;
import com.fattyCorps.common.packet.PacketMap;
import com.fattyCorps.common.packet.dto.DItem;
import com.fattyCorps.common.packet.hero.Hero;
import com.fattyCorps.game.cache.PlayerCache;
import com.fattyCorps.game.obj.cache.PlayerInfo;
import com.fattyCorps.game.obj.db.PlayerData;
import com.fattyCorps.game.obj.msg.HttpStatus;
import com.fattyCorps.game.obj.msg.SRet;
import com.fattyCorps.game.obj.msg.server.battle.SMainGuanqia;
import com.fattyCorps.game.service.player.PlayerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BattleService {
    @Value("${fatty-crops.battle:http://127.0.0.1:8082}")
    String battleServer;

    @Autowired
    PlayerCache playerCache;

    @Autowired
    PlayerService playerService;

    @Autowired
    ItemService itemService;

    public SRet mainGuanqia(int playerId) {
        PlayerInfo playerInfo = playerCache.getPlayerInfo(playerId);
        PlayerData playerData = playerInfo.getPlayerData();
        MainGuanqianMould cfg = SpringUtil.getBean(Cfg.class).getCfg(MainGuanqianMould.class, playerData.getGuanqia());

        CBattle msg = new CBattle();
        msg.setLeftTeam(getSelfTeamInfo(playerData));
        msg.setRightTeam(cfg.getEnemies());

        SRet<SBattleResult> res = remoteCall("battle", msg);
        List<DItem> baseAwards = cfg.getBaseAwards();

        if (res.getData().getBr().equals(EBattleResult.Win)) {
            // 过关
            playerService.passGuanQia(playerId);
            itemService.addItemBatch(playerId, baseAwards);
        }

        SMainGuanqia sMsg = new SMainGuanqia();
        sMsg.setBattleResult(res.getData());
        sMsg.setAwards(baseAwards);

        return SRet.success(sMsg);
    }

    private List<DHeroShort> getSelfTeamInfo(PlayerData playerData) {
        List<Integer> def = playerData.getDefLineupHeroIds();
        PacketMap<Hero> heroes = playerData.getHeroes();
        List<DHeroShort> heroShorts = new ArrayList<>();

        for (int i = 0; i < def.size(); i++) {
            int heroId = def.get(i);
            if (heroId <= 0) {
                continue;
            }

            int posNo = i + 1;
            Hero hero = heroes.get(heroId);
            if (hero == null) {
                continue;
            }

            DHeroShort dHeroShort = new DHeroShort();
            dHeroShort.setPosNo(posNo);
            dHeroShort.setTypeId(hero.getTypeId());
            dHeroShort.setLv(hero.getLv());
            dHeroShort.setStar(hero.getStar());
            heroShorts.add(dHeroShort);
        }

        return heroShorts;
    }

    public SRet test() {
        return remoteCall("testPost", null);
    }

    public <T> SRet remoteCall(String uri, T msg) {
        String url = battleServer + "/battle/" + uri;

        try {
            String result = HttpRequest.post(url)
                    .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                    .body(JSONUtil.toJsonStr(msg))
                    .timeout(20000)//超时，毫秒
                    .execute().body();

            SRet bean = JSONUtil.toBean(result, SRet.class);
            if (bean.getCode().equals(HttpStatus.SUCCESS.getCode())) {
                String jsonStr = JSONUtil.toJsonStr(bean.getData());
                bean.setData(JSONUtil.toBean(jsonStr, SBattleResult.class));
                return bean;
            } else {
                return SRet.error(bean.getCode(), bean.getMsg());
            }
        } catch (Exception e) {
            throw e;
        }
    }
}
